﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using Jalal.Library.Web;

namespace Jalal.Library.Data
{
    public class SqlDataMiner : DataMiner
    {
        public override void AddParameter(DbCommand command, string parameterId, DbType parameterType,
            int parameterSize, ParameterDirection parameterDirection, object parameterValue)
        {
            // Validate Parameter Properties
            if (command == null)
                throw (new ArgumentNullException("command"));
            if (parameterId == null)
                throw (new ArgumentNullException("parameterId"));
            if (parameterId.Length == 0)
                throw (new ArgumentOutOfRangeException("parameterId"));

            // Add Parameter
            SqlParameter newSqlParam = new SqlParameter();
            newSqlParam.ParameterName = parameterId;
            newSqlParam.SqlDbType = ConverToSqlDbType(parameterType);
            newSqlParam.Direction = parameterDirection;

            if (parameterSize > 0)
                newSqlParam.Size = parameterSize;

            if (parameterValue != null)
                newSqlParam.Value = parameterValue;

            command.Parameters.Add(newSqlParam);
        }

        protected override DbConnection Connection
        {
            get
            {
                _connection = SessionManager.Connection;
                if(_connection==null)
                {
                    _connection = new SqlConnection(WebConfigurationManager.ConnectionStrings[SiteConfigSection.SiteConfiguration.ConnectionStringName].ConnectionString);
                    SessionManager.Connection = _connection;
                }
                return _connection;
            }
        }

        private SqlDbType ConverToSqlDbType(DbType type)
        {
            if (type == DbType.String)
                return SqlDbType.NVarChar;
            else if (type == DbType.DateTime)
                return SqlDbType.DateTime;
            else if (type == DbType.Boolean)
                return SqlDbType.Bit;
            else if (type == DbType.Decimal)
                return SqlDbType.Decimal;
            else if (type == DbType.Int32)
                return SqlDbType.Int;
            else if (type == DbType.Xml)
                return SqlDbType.Xml;
            else if (type == DbType.Guid)
                return SqlDbType.UniqueIdentifier;
            else
                return SqlDbType.NVarChar;
        }
    }
}
